package com.dukeindie.wechat.controller

import com.dukeindie.wechat.bean.WXAppConfig
import com.qq.weixin.mp.aes.SHA1
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.*
import javax.servlet.http.HttpServletRequest

@RestController
@RequestMapping
class MainController(val wxAppConfig: WXAppConfig) {
    val logger: Logger = LoggerFactory.getLogger(MainController::class.java)

    /**
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 随机字符串
     */
    @GetMapping(value = ["", "/"])
    fun urlCheck(signature: String,
                 echostr: String,
                 timestamp: String,
                 nonce: String,
                 request: HttpServletRequest): String {
//        var tempStr = listOf<String>(timestamp, nonce, echostr).sortedBy { it }.joinToString("")
        for (entry in request.parameterMap) {
            logger.info("${entry.key} = ${request.getParameter(entry.key)}")
        }

        val testSignature = SHA1.getSHA1(timestamp, nonce, wxAppConfig.token, "")

        if (Objects.equals(testSignature, signature)) {
            return echostr
        } else {
            return "failed"
        }
    }

    @GetMapping("/health")
    fun index(): Map<String, Any> {
        val json = HashMap<String, Any>()
        json["state"] = true
        json["result"] = Date()
        json["appId"] = wxAppConfig.appid
        json["appSecret"] = wxAppConfig.appsecret
        json["token"] = wxAppConfig.token
        return json
    }
}